<template>
    <div class="tasks">
        <el-card>
            <template #header>
                <div class="card-header">
                    <h3>任务管理</h3>
                    <el-button type="primary" @click="handleAdd">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        添加任务
                    </el-button>
                </div>
            </template>

            <el-table :data="tasks" style="width: 100%">
                <el-table-column prop="name" label="任务名称" />
                <el-table-column label="关联设备">
                    <template #default="{ row }">
                        {{ getDeviceLabel(row.device) }}
                    </template>
                </el-table-column>
                <el-table-column prop="schedule" label="执行时间" />
                <el-table-column prop="status" label="状态">
                    <template #default="{ row }">
                        <el-tag :type="row.status === '已完成' ? 'success' : 'warning'">
                            {{ row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="{ row }">
                        <el-button-group>
                            <el-button type="primary" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="danger" @click="handleDelete(row)">删除</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加/编辑任务对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加任务' : '编辑任务'" width="500px">
            <el-form :model="taskForm" :rules="rules" ref="taskFormRef" label-width="80px">
                <el-form-item label="任务名称" prop="name">
                    <el-input v-model="taskForm.name" />
                </el-form-item>
                <el-form-item label="关联设备" prop="device">
                    <el-select v-model="taskForm.device" placeholder="请选择设备" @change="handleDeviceChange">
                        <el-option v-for="device in devices" :key="device.value" :label="device.label"
                            :value="device.value">
                            <span>{{ device.label }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">
                                {{ device.status ? '在线' : '离线' }}
                            </span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="执行时间" prop="schedule">
                    <el-time-picker v-model="taskForm.schedule" format="HH:mm" placeholder="选择时间" style="width: 100%" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select v-model="taskForm.status" placeholder="请选择状态" :disabled="!getSelectedDeviceStatus">
                        <el-option label="待执行" value="待执行" />
                        <el-option label="已完成" value="已完成" />
                    </el-select>
                    <div v-if="taskForm.device && !getSelectedDeviceStatus" class="status-warning">
                        设备当前处于离线状态，无法设置任务状态
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { taskService, deviceService } from '../api/services'
import type { Task, Device } from '../types'

const tasks = ref<Task[]>([])
const devices = ref<{ value: string; label: string; status: boolean }[]>([])

const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const taskFormRef = ref<FormInstance>()

const taskForm = reactive({
    id: 0,
    name: '',
    device: '',
    schedule: '',
    status: '待执行'
})

const rules = {
    name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
    device: [{ required: true, message: '请选择关联设备', trigger: 'change' }],
    schedule: [{ required: true, message: '请选择执行时间', trigger: 'change' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const resetForm = () => {
    taskForm.id = 0
    taskForm.name = ''
    taskForm.device = ''
    taskForm.schedule = ''
    taskForm.status = '待执行'
}

const handleAdd = () => {
    dialogType.value = 'add'
    resetForm()
    dialogVisible.value = true
}

const handleEdit = (row: Task) => {
    dialogType.value = 'edit'
    Object.assign(taskForm, row)
    dialogVisible.value = true
}

const loadDevices = async () => {
    try {
        const response = await deviceService.getAllDevices()
        devices.value = response.data.map(device => ({
            value: device.name,
            label: `${device.name} (${device.location})`,
            status: device.status
        }))
    } catch (error: any) {
        ElMessage.error(error.message || '加载设备列表失败')
    }
}

const loadTasks = async () => {
    try {
        const response = await taskService.getAllTasks()
        tasks.value = response.data.map((task: Task) => ({
            ...task,
            schedule: task.schedule
        }))
    } catch (error: any) {
        ElMessage.error(error.message || '加载任务列表失败')
    }
}

const handleDelete = async (row: Task) => {
    try {
        await ElMessageBox.confirm('确定要删除该任务吗？', '提示', {
            type: 'warning'
        })
        await taskService.deleteTask(row.id)
        tasks.value = tasks.value.filter(item => item.id !== row.id)
        ElMessage.success('删除成功')
    } catch (error: any) {
        if (error !== 'cancel') {
            ElMessage.error(error.message || '删除失败，请重试')
        }
    }
}

const handleSubmit = async () => {
    if (!taskFormRef.value) return

    try {
        await taskFormRef.value.validate(async (valid) => {
            if (valid) {
                // 检查设备状态
                const selectedDevice = devices.value.find(d => d.value === taskForm.device)
                if (!selectedDevice?.status) {
                    ElMessage.error('无法添加任务：选择的设备当前处于离线状态')
                    return
                }

                const taskData = {
                    name: taskForm.name,
                    device: taskForm.device,
                    schedule: taskForm.schedule,
                    status: taskForm.status
                }

                if (dialogType.value === 'add') {
                    const response = await taskService.addTask(taskData)
                    tasks.value.push(response.data)
                    ElMessage.success('添加成功')
                } else {
                    const response = await taskService.updateTask(taskForm.id, taskData)
                    const index = tasks.value.findIndex(item => item.id === taskForm.id)
                    if (index !== -1) {
                        tasks.value[index] = response.data
                    }
                    ElMessage.success('更新成功')
                }

                dialogVisible.value = false
            }
        })
    } catch (error: any) {
        ElMessage.error(error.message || '操作失败，请重试')
    }
}

// 添加设备状态变化监听
const handleDeviceChange = () => {
    if (taskForm.device) {
        const selectedDevice = devices.value.find(d => d.value === taskForm.device)
        if (!selectedDevice?.status) {
            taskForm.status = '待执行'
            ElMessage.warning('所选设备当前离线，任务状态已重置为待执行')
        }
    }
}

const getDeviceLabel = (deviceName: string) => {
    const device = devices.value.find(d => d.value === deviceName)
    return device ? device.label : deviceName
}

const getSelectedDeviceStatus = computed(() => {
    const selectedDevice = devices.value.find(d => d.value === taskForm.device)
    return selectedDevice?.status || false
})

onMounted(async () => {
    await Promise.all([loadTasks(), loadDevices()])
})
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header h3 {
    margin: 0;
    font-size: 18px;
    color: #303133;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.status-warning {
    color: #E6A23C;
    font-size: 12px;
    margin-top: 5px;
}
</style>